package com.maybach.redis.impl;

import com.maybach.redis.IRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Created by houenxun on 16/1/7.
 */
public class RedisRepository implements IRedisRepository {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Object get(String key) {
        return redisTemplate.boundValueOps(key).get();
    }

    @Override
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public StringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public <V> void set(String key, V value) {
        this.set(key, value, -1L);
    }

    @Override
    public <V> void set(String key, V value, long timeMillis) {

        ((BoundValueOperations) (redisTemplate.boundValueOps(key))).set(value);
        if (timeMillis > 0) {
            redisTemplate.expire(key, timeMillis, TimeUnit.MILLISECONDS);
        }

    }

    @Override
    public <T> T get(String key, Class<T> t) {
        return (T) this.get(key);
    }
}
